package net.jueb.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
/**
 * 占用一个端口，然后广播数据和接收数据
 * @author helin
 */
public class UdpServer {
	
	/**
	 * 广播和接收udp数据的端口
	 * @param port
	 */
	public void start(int port)
	{
		NioEventLoopGroup group=new NioEventLoopGroup();
		Bootstrap bt=new Bootstrap();
		bt.group(group);
		bt.channel(NioDatagramChannel.class);
		//SO_BROADCAST 允许广播地址发送和接收信息包。只对UDP有效
		bt.option(ChannelOption.SO_BROADCAST, true);//广播支持
		bt.handler(new UdpServerHandler());
		try {
			ChannelFuture cf = bt.bind(port).sync();
			System.out.println("UDP服务端启动成功,端口："+port);
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new UdpServer().start(80);
	}
}
